package com.service.devimonitor;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.bpms.common.VO;
import com.service.util.DateUtil;
import com.zk.atm.forms.BaseForm;
import com.zk.atm.utils.AccessDBConnection;
import com.zk.atm.utils.StringUtil;
import com.zk.atm.vo.BaseVo;
/**
*
* <p>Title:运用类反射机制来实现 </p>
* <p>Description:持久化层DAO层简化:通用查询类 </p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company:scitel.co.,ltd </p>
* @author zhujw来源于IBM社区
* @version 1.0
*/
public class AtmpStatusCurrentReflect {

	  private static Logger logger = Logger.getLogger(AtmpStatusCurrentReflect.class);
	  private Connection con = null;
	  private PreparedStatement pstmt = null;
	  private ResultSet rs = null;

	  /**
	   * 完成ResultSet对象向ArrayList对象为集合的对象的转化
	   * @param sql,指定的查询Sql
	   * @param className,Sql相对应的JavaBean/FormBean类的名字:具体的Vo值对象或ActionForm
	   * @Return:以类className为一条记录的结果集，
	   * 完成ResultSet对象向ArrayList对象为集合的className对象的转化
	   */
	  public List getListByClassName(String sql, String className) throws Exception {
	    ArrayList arr = null; //数组来处理
	    try {
	       con = AccessDBConnection.getConnection(); //取得数据库连接
	      pstmt = con.prepareStatement(sql);
	      rs = pstmt.executeQuery(); //执行查询
	      Object recordValue = ""; //构造返回的结果集
	      
	      Object c1 = null;
	      arr = new ArrayList();
	      ResultSetMetaData rsmd = rs.getMetaData(); //取得数据表中的字段数目，类型等返回结果
	      //是以ResultSetMetaData对象保存
	      int columnCount = rsmd.getColumnCount(); //列的总数
	      
	      while (rs.next()) {
	    	  c1 = Class.forName(className).newInstance(); //类的实例化
	        for (int i = 1; i <= columnCount; i++) {
	        	String column_name=rsmd.getColumnName(i).toLowerCase();
	        	String methodName=getSetMethodName(column_name);
	        	Field field=null;
	        	Method m=null;
				try {
					field = c1.getClass().getDeclaredField(column_name);
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
	        	if(field==null){
	        		continue;
	        	}
	        	String column_value="";
	        	String field_type=field.getType().getName();
	        	if(field_type.equals("java.lang.String")){
	        		column_value=StringUtil.getPropertyValue(rs.getString(column_name));
	        		recordValue=new String();
	        		recordValue=column_value;
	        	}else if(field_type.equals("java.util.Date")){
	        		String d1=rs.getString(column_name);
	        		if(d1==null){
	        			continue;
	        		}
	        		Date d=DateUtil.getInstance().getDate(d1, "yyyy-MM-dd hh:mm:ss");
	        		recordValue=new Date();
	        		recordValue=d;
	        	}else if(field_type.equals("java.lang.Long")){
	        		Long value=rs.getLong(column_name);
	        		recordValue=new Long(-1);
	        		recordValue=value;
	        	}
	        	if(recordValue==null){
	        		continue;
	        	}
				try {
					m = c1.getClass().getMethod(methodName,new Class[] {recordValue.getClass()});
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
	        	if(m==null){
	        		continue;
	        	}
   	            m.invoke(c1, new Object[] {recordValue});
                //System.out.println("************第"+i+"次:方法名是="+methodName);
	        }
	       // log.info("取得ActionForm或VO中的set方法" +  getSetMethodName(rsmd.getColumnName(1)));
	        arr.add(c1);
	      }

	    } catch (Exception e) {
	    	e.printStackTrace();
	    }finally {
	      AccessDBConnection.closeConnection(con); //释放资源
	    }
	    return arr;

	  }

	  /**根据字段的名字返回相应的set方法的名字
	   * 例如：字段名称为chkr_code考核规则设置编码
	   * 调用此方法得到：setChkr_code
	   * @param string
	   * @return:利用StringBuffer来优化性能
	   */
	  public String getSetMethodName(String columnName) {

	    String ret = "";
	    columnName = columnName.toLowerCase();
	    String first_char=columnName.substring(0,1).toUpperCase();
	    StringBuffer sb = new StringBuffer();
	    sb.append("set");
	    sb.append(first_char+columnName.substring(1, columnName.length())); //其他字符小写，符合JavaBean的命名规则
	    ret = sb.toString();
	    //System.out.println("ret="+ret);
	    return ret;
	  }

	  /**
	   * @param args
	   */
	  public static void main(String[] args) {
	    //方法测试通过
	    String sql =
	        "select * from atmp_device_status_current "; //查询告警用户过滤设置明细
	    AtmpStatusCurrentReflect reflect=new AtmpStatusCurrentReflect();
	    List arr=null;
		try {
			arr = reflect.getListByClassName(sql, "com.zk.atm.vo.AtmpDeviceStatusCurrent");
			System.out.println("集合大小------>>>>>>>" + arr.size());
			for (Object object : arr) {
				System.out.println(object.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	    //System.out.println("集合大小------>>>>>>>"+arr.toArray().toString());
	}
	  
	  protected static String getGetterMethod(String column_name) throws Exception{
			String getter_method="get";
			column_name=column_name.substring(0,1).toUpperCase()+column_name.substring(1,column_name.length());
			getter_method+=column_name;
			if(logger.isDebugEnabled()){
			  System.out.println("getter_method="+getter_method);
			}
			return getter_method;
	}
	  
	  public static VO getAtmpVOByClass(BaseVo ad) throws Exception{
			VO vo=new VO();
			Field[] fields=ad.getClass().getDeclaredFields();
			 for (Field field : fields) {
					String field_name=field.getName();
					//System.out.println(field_name);
					String method_name=getGetterMethod(field_name);
					if(method_name.equals("")){		
						continue;
					}
					Method m=null;
					try {	
						m=ad.getClass().getMethod(method_name);		
					} catch (Exception e) {
						e.printStackTrace();
						continue;
					}
					if(m==null){
						continue;
					}
					String type_name=field.getType().getName().toString();
					Object value=null;
					if(type_name.equals("java.lang.String")){
						value=new String();
					    value=(String)m.invoke(ad);
					}else if(type_name.equals("java.lang.Long")){
						value=new Long(-1);
						value=m.invoke(ad);
					}else if(type_name.equals("java.util.Date")){
						value=new Date();
						value=m.invoke(ad);
					}else{
						value="";
					}
					if(value!=null){
						if(logger.isDebugEnabled()){
						  System.out.println("getAtmpVOByClass:reflect:value="+value.toString());
						}
						vo.setObj(field_name, value);
					}
			  }
			 return vo;
		}
	  
	  public static boolean executeSaveOrDelBySql(BaseForm form) throws Exception{
			boolean is_success=false;
			String sql=StringUtil.getPropertyValue(form.getExec_sql());
			if(sql.equals("")){
				return is_success;
			}
			Connection conn=null;
			try {
				conn=AccessDBConnection.getConnection();
				PreparedStatement pst=conn.prepareStatement(sql);
				pst.execute(sql);
				is_success=true;
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				AccessDBConnection.closeConnection(conn);
			}
			return is_success;
		}

}
